package com.ml.loan.common.utils.http;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class HttpClientUtil {

    private static final String JSON_CONTENT_TYPE_PREFIX = "application/json;charset=";

    private static final String HEADER_CONTENT_TYPE = "content-type";

    private static final String UTF8 = "UTF-8";

    private static final int maxTotal = 100;

    private static final int maxPerRoute = 100;

    private static PoolingHttpClientConnectionManager connectionManager;


    /**
     * 初始化连接池
     */
    static {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            // 初始化连接管理器
            connectionManager = new PoolingHttpClientConnectionManager(reg);
            // 设置最大路由
            connectionManager.setDefaultMaxPerRoute(maxPerRoute);
            // 设置最大连接数
            connectionManager.setMaxTotal(maxTotal);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            log.error("HttpClientPool:{}", e.getMessage(), e);
        }
    }

    public HttpClientUtil() {
    }

    public static CloseableHttpClient getClient(RequestConfig requestConfig) {
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        // 设置连接池管理
        httpClientBuilder.setConnectionManager(connectionManager);
        // 设置请求配置
        if (requestConfig != null) {
            httpClientBuilder.setDefaultRequestConfig(requestConfig);
        }
        // 设置重试次数
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
        //设置共享连接池
        httpClientBuilder.setConnectionManagerShared(true);
        return httpClientBuilder.build();
    }

    public static CloseableHttpClient getClient() {
        return getClient(null);
    }


    /**
     * 生成表单请求实体
     */
    private static UrlEncodedFormEntity prepareFromEntity(Map<String, Object> paramMap) throws UnsupportedEncodingException {
        if (paramMap != null) {
            List<BasicNameValuePair> params = new ArrayList<>();
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            return new UrlEncodedFormEntity(params, UTF8);
        } else {
            return null;
        }
    }


    /**
     * 生成json格式请求实体
     */
    private static StringEntity prepareStringEntity(Map<String, Object> paramMap) {
        if (paramMap != null) {
            StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(paramMap), UTF8);
            stringEntity.setContentType(JSON_CONTENT_TYPE_PREFIX + UTF8);
            return stringEntity;
        } else {
            return null;
        }
    }


    public static CustomHttpResp post(HttpContentTypeEnum contentTypeEnum, String url, Map<String, Object> paramas, Map<String, String> headers, RequestConfig requestConfig) {
        CustomHttpResp customHttpResp = CustomHttpResp.builder().httpStatus(HttpStatus.SC_CONTINUE).build();
        if (requestConfig == null) {
            requestConfig = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
        }
        CloseableHttpClient client = getClient(requestConfig);
        HttpPost httpPost = new HttpPost(url);
        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        /* 添加请求参数 */
        HttpEntity entity = null;
        CloseableHttpResponse resp = null;
        try {
            if (contentTypeEnum == HttpContentTypeEnum.APPLICATION_FORM) {
                httpPost.setHeader(HEADER_CONTENT_TYPE, HttpContentTypeEnum.APPLICATION_FORM.getContentType());
                entity = prepareFromEntity(paramas);
            }
            if (contentTypeEnum == HttpContentTypeEnum.APPLICATION_JSON) {
                httpPost.setHeader(HEADER_CONTENT_TYPE, HttpContentTypeEnum.APPLICATION_JSON.getContentType());
                entity = prepareStringEntity(paramas);
            }
            if (entity != null) {
                httpPost.setEntity(entity);
            }
            resp = client.execute(httpPost);
            if (Objects.nonNull(resp) && Objects.nonNull(resp.getEntity())) {
                customHttpResp.setHttpStatus(resp.getStatusLine().getStatusCode());
                customHttpResp.setHttpBody(EntityUtils.toString(resp.getEntity(), "UTF-8"));
            }
        } catch (IOException e) {
            log.error("HttpClientUtil.post:{}", e.getMessage(), e);
            customHttpResp.setHttpStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } finally {
            try {
                if (resp != null) {
                    resp.close();
                }
            } catch (Exception e) {
                log.error("HttpClientUtil.post:{}", e.getMessage(), e);
            }
        }
        return customHttpResp;
    }

    public static CustomHttpResp batchUploadFile(String url, MultipartFile[] multipartFiles) {
        CustomHttpResp customHttpResp = CustomHttpResp.builder().httpStatus(HttpStatus.SC_CONTINUE).build();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000).setSocketTimeout(22000).build();
        CloseableHttpClient client = getClient(requestConfig);
        HttpPost httpPost;
        CloseableHttpResponse resp = null;
        try {
            httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (MultipartFile multipartFile : multipartFiles) {
                builder.addBinaryBody("file", multipartFile.getInputStream(),
                        ContentType.create("multipart/form-data"), multipartFile.getOriginalFilename());
            }
            httpPost.setEntity(builder.build());
            resp = client.execute(httpPost);
            if (Objects.nonNull(resp) && Objects.nonNull(resp.getEntity())) {
                customHttpResp.setHttpStatus(resp.getStatusLine().getStatusCode());
                customHttpResp.setHttpBody(EntityUtils.toString(resp.getEntity(), "UTF-8"));
            }
        } catch (Exception e) {
            log.error("HttpClientUtil.batchUploadFile:{}", e.getMessage(), e);
            customHttpResp.setHttpStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        } finally {
            if (resp != null) {
                try {
                    resp.close();
                } catch (IOException e) {
                    log.error("HttpClientUtil.batchUploadFile:{}", e.getMessage(), e);
                }
            }
        }
        return customHttpResp;
    }

}
